﻿using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using Quartz;
using Spider.Data;
using Spider.DataAccess;
using Spider.Util;
using Spider.Util;

namespace Spider.ScheduledTask
{
    public class CrawlerJob : IJob
    {
        string baseUri = ConfigurationManager.AppSettings["baseUri"];
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                dynamic stocks = StockDAL.GetStocks(1, int.MaxValue, true);
                if (stocks.rows != null && stocks.rows.Count > 0)
                {
                    AsyncQueue queue = new AsyncQueue();
                    foreach (dynamic stock in stocks.rows)
                    {
                        string adress = baseUri + stock.szonecode + stock.scode;
                        HttpWebRequest req = HttpWebRequest.Create(adress) as HttpWebRequest;
                        req.Method = "GET";
                        IAsyncResult ar = req.BeginGetResponse(null, null);
                        queue.Attach(ar, (result) =>
                        {
                            using (HttpWebResponse rsp = req.EndGetResponse(result) as HttpWebResponse)
                            {
                                Stream stream = rsp.GetResponseStream();
                                StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("GBK"));
                                string info = sr.ReadToEnd();
                                int startIndex = info.IndexOf("\"") + 1;
                                string[] details = info.Substring(startIndex, info.Length - startIndex - 1).Split(',');
                                ProcessData(details, stock.sid);
                                sr.Close();
                                stream.Close();
                                rsp.Close();
                            }
                        });
                    }
                    queue.ExecuteCallback();
                }
            }
            catch (Exception e)
            {
                Logger.Error(e.StackTrace.ToString());
            }
        }
        private void ProcessData(string[] details,object sid)
        {
            dynamic obj = new SmartObject();
            obj.openprice = decimal.Parse(details[1]);
            obj.closeprice = decimal.Parse(details[2]);
            obj.volume = decimal.Parse(details[8]);
            obj.turnover = decimal.Parse(details[9]);
            obj.tradedate =DateTime.Parse(details[30]+" "+details[31]);
            obj.sid = sid;
            StockDAL.InsertTrade(obj);
        }
    }
}
